package com.java8.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * java8 内置的四大核心函数式接口
 * Consumer<T>：消费型接口
 * void accept(T t)
 * <p>
 * Supplier<T>:供给型接口
 * T get();
 * <p>
 * Function<T, R>: 函数型接口
 * R apply(T t);
 * <p>
 * Predicate<T>:断言型接口
 * boolean test(T t);
 */
public class TestLambda3 {

    //Predicate<T> 断言型接口:
    @Test
    public void test4() {
        List<String> list = Arrays.asList("Hello", "atguigu", "java8");
        List<String> stringList = filterStr(list, (s) -> s.length() > 3);
        System.out.println(stringList);
    }

    //需求:将满足条件的字符串，放入集合
    public List<String> filterStr(List<String> list, Predicate<String> predicate) {
        List<String> stringList = new ArrayList<>();
        for (String str : list) {
            if (predicate.test(str)) {
                stringList.add(str);
            }
        }
        return stringList;
    }

    //Function<T,R> 函数型接口:
    @Test
    public void test3() {
        String s1 = strHandler("/t/t/t 我大尚硅谷威武", (s) -> s.trim());
        System.out.println(s1);

        String s2 = strHandler("薛虎威武！！", (s) -> s.substring(2, 5));
        System.out.println(s2);
    }

    //需求:用于处理字符串
    private String strHandler(String str, Function<String, String> fun) {
        return fun.apply(str);
    }

    //Supplier<T> 供给型接口:
    @Test
    public void test2() {
        List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
        numList.forEach(System.out::println);
    }

    //产生一些整数，并放入集合中
    public List<Integer> getNumList(int num, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<>();

        for (int i = 0; i < num; i++) {
            Integer integer = supplier.get();
            list.add(integer);
        }
        return list;
    }

    //Cosumer<T> 消费型接口
    @Test
    public void test1() {
        happy(1000, m -> {
            System.out.println("消费" + m);
        });
    }

    private void happy(double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }


}
